package net.lahuobao.mall.service.impl.admin;

import com.alibaba.fastjson.JSONObject;
import net.lahuobao.mall.dao.admin.MallProjectUpdateLogMapper;
import net.lahuobao.mall.dao.admin.MallTransProjectEmployeeMapper;
import net.lahuobao.mall.dao.admin.MallTransProjectMapper;
import net.lahuobao.mall.entity.admin.*;
import net.lahuobao.mall.entity.admin.querymodel.MallProjectEmployeeModel;
import net.lahuobao.mall.entity.admin.querymodel.MallProjectModel;
import net.lahuobao.mall.entity.admin.resultmodel.MallProjectEmployee;
import net.lahuobao.mall.service.admin.MallProjectServiceI;
import org.apache.commons.lang.StringUtils;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.*;

/**
 * Created by Lenovo on 2017/3/22.
 */
@Service("mallProjectService")
@Transactional
public class MallProjectServiceImpl implements MallProjectServiceI {
    @Autowired
    private MallProjectUpdateLogMapper mallProjectUpdateLogMapper;
    @Autowired
    private MallTransProjectEmployeeMapper mallTransProjectEmployeeMapper;
    @Autowired
    private MallTransProjectMapper mallTransProjectMapper;

    @Override
    public DataGrid getTransProjectALL(Map map) {
        DataGrid dg = new DataGrid();
        MallProjectModel model = new MallProjectModel();
        model.setProjectName((String)map.get("search"));
        model.setIsPage((String)map.get("isPage"));
        model.setUserName((String)map.get("userName"));
        if(StringUtil.isNotEmpty(model.getIsPage())&&"true".equals(model.getIsPage())){
            model.setLimit(Integer.valueOf((String)map.get("limit")));
            model.setOffset(Integer.valueOf((String)map.get("offset")));
        }

        int count = mallTransProjectMapper.selectAllCount(model);
        List<MallTransProject> prjList = mallTransProjectMapper.selectAll(model);
        dg.setTotal(count);
        dg.setResults(prjList);
        return dg;
    }

    @Override
    public DataGrid getProjectEmployee(Map map) {
        DataGrid dg = new DataGrid();
        MallProjectEmployeeModel employeeModel = new MallProjectEmployeeModel();
        employeeModel.setIsPage((String)map.get("isPage"));
        if("true".equals(employeeModel.getIsPage())){
            employeeModel.setLimit(Integer.valueOf((String)map.get("limit")));
            employeeModel.setOffset(Integer.valueOf((String)map.get("offset")));
        }
        employeeModel.setProjectName((String)map.get("projectName"));
        if(map.containsKey("projectId") && StringUtil.isNotEmpty(map.get("projectId"))){
            employeeModel.setProjectId(Integer.valueOf((String) map.get("projectId")));
        }
        String search = (String)map.get("search");
        if(StringUtil.isNotEmpty(search)){
            employeeModel.setSearch('%'+search+'%');
        }
        if(map.containsKey("employeeId")&&StringUtil.isNotEmpty((Integer)map.get("employeeId"))){
            employeeModel.setEmployeeId((Integer)map.get("employeeId"));
        }
        int count = mallTransProjectMapper.getProjectEmployeeCount(employeeModel);
        List<MallProjectEmployee> prjEmpList = mallTransProjectMapper.getProjectEmployee(employeeModel);
        addAccessRule((String)map.get("userId"),prjEmpList);
        dg.setTotal(count);
        dg.setResults(prjEmpList);
        return dg;
    }

    private void addAccessRule(String accountId,List<MallProjectEmployee> prjEmpList){
        MallCardRole cardRole = getUserCardRole(accountId);
        if(cardRole!=null){
            if(cardRole.getCode()==0){
                if(prjEmpList!=null && prjEmpList.size()>0){
                    for(MallProjectEmployee emp : prjEmpList){
                            emp.setRole(1);
                    }
                }
                return;
            }else if(cardRole.getCode()==1){
                List<MallTransProjectEmployee> userRoles = getAccountAdminEmployees(accountId);
                HashSet<Integer> prjSet = new HashSet<Integer>();
                if(userRoles!=null&&userRoles.size()>0){
                    for(MallTransProjectEmployee role : userRoles){
                        prjSet.add(role.getProjectid());
                    }
                }
                if(prjEmpList!=null && prjEmpList.size()>0){
                    for(MallProjectEmployee emp : prjEmpList){
                        if(prjSet.contains(emp.getProjectId())){
                            emp.setRole(1);
                        }else{
                            emp.setRole(0);
                        }
                    }
                }
                return;
            }
        }
        if(prjEmpList!=null && prjEmpList.size()>0){
            for(MallProjectEmployee emp : prjEmpList){
                emp.setRole(0);
            }
        }
    }

    /**
     *
     * @param map
     * employeeId userName realName projectId
     * @throws Exception
     */
    @Override
    public void modifyProjectEmployeeInfo(Map map) throws Exception{
        String empId = (String) map.get("employeeId");
        String userId = (String)map.get("userId");
        String userName = (String) map.get("userName");
        String accountNo = (String) map.get("accountNo");
        String isAdmin = (String)map.get("isAdmin");
        String projectId = (String)map.get("projectId");
        if(StringUtils.isNotEmpty(empId)){

            List<LhbUser> lhbs = getLHBUser(userName, "");
            /** 查看工程下是否存在相同拉货宝用户 **/
//            List<MallProjectEmployee> mallProjectEmployees = getProjectEmp(userName,"",projectId);
//            if(mallProjectEmployees!=null&&mallProjectEmployees.size()>0){
//                throw new Exception("用户帐号已存在,请不要重复添加");
//            }
            MallTransProjectEmployee dbEmployee = mallTransProjectEmployeeMapper.selectByPrimaryKey(Integer.valueOf(empId));
            Map accountingQuery = new HashMap();
            accountingQuery.put("accountNo", accountNo);
            String accountId = mallTransProjectEmployeeMapper.selectAccountIdByAccountNo(accountingQuery);
            if(accountId == null || accountId.equals("")){
                throw new Exception("账务账号不存在");
            }
            accountingQuery.remove("accountNo");
            accountingQuery.put("projectId", projectId);
            int count = mallTransProjectEmployeeMapper.totalAccountNoByProjectId(accountingQuery);
            if(count > 0){
                accountingQuery.put("accountNo", accountNo);
                accountingQuery.put("userId", userId);
                count = mallTransProjectEmployeeMapper.totalAccountNoByProjectId(accountingQuery);
                if(count > 0){
                    throw new Exception("相同项目财务账号不能相同");
                }
            }

            if(dbEmployee!= null&&lhbs!=null&&lhbs.size()>0){
                dbEmployee.setUpdatetime(new Date());
                dbEmployee.setUpdateuserid((String)map.get("userId"));
                dbEmployee.setProjectid(Integer.valueOf(projectId));
                dbEmployee.setRealname((String)map.get("realName"));
                dbEmployee.setUserid(lhbs.get(0).getUserId());
                dbEmployee.setAccountid(accountId);
                dbEmployee.setIsadmin(isAdmin.equals("1"));
                mallTransProjectEmployeeMapper.updateByPrimaryKey(dbEmployee);
                if(dbEmployee.getIsadmin()){
                    Map projectEmployeeUpdate = new HashMap();
                    projectEmployeeUpdate.put("projectId", projectId);
                    projectEmployeeUpdate.put("userId", dbEmployee.getUserid());
                    mallTransProjectEmployeeMapper.updateIsAdmin(projectEmployeeUpdate);
                }
            }else{
                throw new Exception("修改用户信息失败,修改的帐号异常，请核对");
            }
        }

    }

    /**
     *
     * @param map
     * projectId userId projectName
     * @throws Exception
     */
    @Override
    public void modifyProjectInfo(Map map) throws Exception {
        String prjId = (String) map.get("projectId");
        String proName = (String)map.get("projectName");

        MallTransProject dbProject = mallTransProjectMapper.selectByPrimaryKey(Integer.valueOf(prjId));
        if(dbProject==null){
            throw new Exception("项目已被删除，请刷新页面");
        }
        if(!dbProject.getProjectname().equals(proName)){
            Map query = new HashMap();
            query.put("projectName",proName);
            int count = getProjectCount(query);
            if(count>0){
                throw new Exception("项目名称已被占用");
            }
        }
        String before = JSONObject.toJSONString(dbProject);
        dbProject.setUpdatetime(new Date());
        dbProject.setUpdateuserid((String)map.get("userId"));
        dbProject.setRemark((String)map.get("projectDescribe"));
        dbProject.setProjectname(proName);
        String after = JSONObject.toJSONString(dbProject);

        mallTransProjectMapper.updateByPrimaryKey(dbProject);
    }

    /**
     *
     * @param map
     * projectName userId
     * @throws Exception
     */
    @Override
    public void addMallProject(Map map) throws Exception {
        String projectName = (String)map.get("projectName");
        String projectDescribe = (String)map.get("projectDescribe");
        if(StringUtils.isEmpty(projectName)){
            throw new Exception("项目名称不能为空");
        }
        Map query = new HashMap();
        query.put("projectName",projectName);
        int count = getProjectCount(query);
        if(count>0){
            throw new Exception("项目名称已被占用");
        }

        MallTransProject project = new MallTransProject();
        project.setProjectname(projectName);
        project.setRemark(projectDescribe);
        project.setCreatetime(new Timestamp(System.currentTimeMillis()));
        project.setCreateuserid((String)map.get("userId"));
        project.setIsdelete(false);
        mallTransProjectMapper.insert(project);

        String logContent = "添加项目:" + JSONObject.toJSONString(project);
    }

    @Override
    public List<MallTransProject> getProject(Map map) {
        return mallTransProjectMapper.getProject(map);
    }

    @Override
    public int getProjectCount(Map map) {
        return mallTransProjectMapper.getProjectCount(map);
    }

    @Override
    public void addProjectEmployee(Map map) throws Exception{
        String projectName = (String)map.get("projectName");
        String projectId = (String)map.get("projectId");
        String userName = (String)map.get("userName");
        String accountNo = (String)map.get("accountNo");
        String isAdmin = (String)map.get("isAdmin");
        String userId = (String)map.get("userId");
        Map userQuery = new HashMap();
        userQuery.put("userName",userName);
        List<LhbUser> users = mallTransProjectMapper.getLHBUser(userQuery);
        if(users==null || users.size()==0){
            throw new Exception("拉货宝帐号不存在，请核对");
        }
        LhbUser user = users.get(0);
        /** 查看工程下是否存在相同拉货宝用户 **/
        List<MallProjectEmployee> mallProjectEmployees = getProjectEmp(userName,projectName,projectId);
        if(mallProjectEmployees!=null&&mallProjectEmployees.size()>0){
            throw new Exception("用户帐号已存在,请不要重复添加");
        }

        Map accountingQuery = new HashMap();
        accountingQuery.put("accountNo", accountNo);
        String accountId = mallTransProjectEmployeeMapper.selectAccountIdByAccountNo(accountingQuery);
        if(accountId == null || accountId.equals("")){
            throw new Exception("账务账号不存在");
        }
        accountingQuery.remove("accountNo");
        accountingQuery.put("projectId", projectId);
        int count = mallTransProjectEmployeeMapper.totalAccountNoByProjectId(accountingQuery);
        if(count > 0){
            accountingQuery.put("accountNo", accountNo);
            accountingQuery.put("userId", userId);
            count = mallTransProjectEmployeeMapper.totalAccountNoByProjectId(accountingQuery);
            if(count > 0){
                throw new Exception("相同项目财务账号不能相同");
            }
        }
        MallTransProjectEmployee record = new MallTransProjectEmployee();
        record.setIsdelete(false);
        record.setCreateuserid((String)map.get("userId"));
        record.setRealname((String)map.get("realName"));
        record.setCreatetime(new Date());
        record.setProjectid(Integer.valueOf(projectId));
        record.setUserid(user.getUserId());
        record.setAccountid(accountId);
        record.setIsadmin(isAdmin.equals("1"));
        mallTransProjectEmployeeMapper.insert(record);
        if(record.getIsadmin()){
            Map projectEmployeeUpdate = new HashMap();
            projectEmployeeUpdate.put("projectId", projectId);
            projectEmployeeUpdate.put("userId", record.getUserid());
            mallTransProjectEmployeeMapper.updateIsAdmin(projectEmployeeUpdate);
        }
    }

    /**
     *
     * @param map
     * projectName or projectId | userId
     * @throws Exception
     */
    @Override
    public void delProject(Map map) throws Exception{
        String projectName =(String)map.get("projectName");
        String projectId =(String)map.get("projectId");
        if(StringUtils.isEmpty(projectName) && StringUtils.isEmpty(projectId)){
            throw  new Exception("参数异常,请输入你要删除的项目名称或ID");
        }
        List<MallTransProject> projects = getProject(map);
        if(projects!=null && projects.size()>0){
            MallTransProject prj = projects.get(0);
            Map query = new HashMap();
            query.put("projectName",prj.getProjectname());
            DataGrid employeeDataGrid = getProjectEmployee(query);
            List<MallProjectEmployee> employees = employeeDataGrid.getResults();
            if(employees!=null && employees.size()>0){
                throw new Exception("项目存在成员不能删除");
            }
            prj.setIsdelete(true);
            prj.setUpdateuserid((String)map.get("userId"));
            prj.setUpdatetime(new Date());
            mallTransProjectMapper.updateByPrimaryKey(prj);
            String logContent = "删除项目:"+JSONObject.toJSONString(prj);
        }
    }

    /**
     *  删除组用户
     * @param map
     *  employeeId | userId
     * @throws Exception
     */
    @Override
    public void delProjectEmployee(Map map) throws Exception{
        String empId = (String)map.get("employeeId");
        if(StringUtils.isEmpty(empId)){
            throw new Exception("请选择你要删除的用户");
        }
        MallTransProjectEmployee dbEmployee = mallTransProjectEmployeeMapper.selectByPrimaryKey(Integer.valueOf(empId));
        if(dbEmployee==null){
            throw new Exception("你要删除的用户不存在");
        }
        dbEmployee.setIsdelete(true);
        dbEmployee.setUpdatetime(new Date());
        dbEmployee.setUpdateuserid((String)map.get("userId"));
        mallTransProjectEmployeeMapper.updateByPrimaryKey(dbEmployee);
        String logContent = "删除用户:" + JSONObject.toJSONString(dbEmployee);
    }

    @Override
    public void addMallLog(String cardNo, String operatorId, int logType, String logcontent) {
        MallProjectUpdateLog record = new MallProjectUpdateLog();
        record.setUpdateuserid(operatorId);
        record.setCardno(cardNo);
        record.setUpdatetime(new Date());
        record.setLogtype(logType);
        record.setLogcontent(logcontent);
        mallProjectUpdateLogMapper.insert(record);
    }

    @Override
    public DataGrid getMallProjectLog(Map map) {
        DataGrid  dg = new DataGrid();
        dg.setResults(mallProjectUpdateLogMapper.selectByQuery(map));
        dg.setTotal(mallProjectUpdateLogMapper.selectByQueryCount(map));
        return dg;
    }

    @Override
    public DataGrid getMallCardInfo(Map map) {
        List<MallShopCardUseInfo> cardInfos = mallTransProjectMapper.getCardNoUseInfo(map);
        int count = mallTransProjectMapper.getCardNoUseInfoCount(map);
        DataGrid dg = new DataGrid();
        dg.setResults(cardInfos);
        dg.setTotal(count);
        return dg;
    }

    @Override
    public MallCardRole getUserCardRole(String userId) {
        return mallTransProjectMapper.getUserCardRole(userId);
    }

    private List<MallProjectEmployee> getProjectEmp(String userName,String projectName,String projectId){
        MallProjectEmployeeModel query = new MallProjectEmployeeModel();
        query.setUserName(userName);
        query.setProjectName(projectName);
        if(StringUtils.isNotEmpty(projectId)){
            query.setProjectId(Integer.valueOf(projectId));
        }
        return mallTransProjectMapper.getProjectEmployee(query);
    }

    private List<LhbUser> getLHBUser(String userName,String userId){
        Map map = new HashMap();
        if(StringUtil.isNotEmpty(userId)) {
            map.put("userId", Integer.valueOf(userId));
        }
        map.put("userName",userName);
        return mallTransProjectMapper.getLHBUser(map);
    }

    public List<MallTransProjectEmployee> getAccountAdminEmployees(String accountId){
       return mallTransProjectEmployeeMapper.getAccountAdminEmployees(accountId);
    }
}
